<template>
  <a-card class="employee-container">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="分类" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="queryForm.materialId" placeholder="分类" />
        </a-form-item>
        <a-form-item label="物料名称" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="queryForm.projectId" placeholder="物料名称" />
        </a-form-item>
        <a-form-item label="型号" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="queryForm.projectMaterialCode" placeholder="型号" />
        </a-form-item>
        <a-form-item label="供应商" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="queryForm.registrant" placeholder="供应商" />
        </a-form-item>
        <a-form-item label="是否禁用" class="smart-query-form-item">
          <a-input style="width: 150px" v-model:value="queryForm.disabledFlag" placeholder="是否禁用" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="queryData">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="btn-group">
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button @click="confirmBatchDelete" type="danger" size="small" :disabled="selectedRowKeyList.length == 0">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>

      <span class="smart-table-column-operate">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.SYSTEM.EMPLOYEE" :refresh="queryEmployee" />
      </span>
    </a-row>
<!-- :row-selection="{ selectedRowKeys: selectedRowKeyList }" //, onChange: onSelectChange -->
    <a-table
      size="small"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      :loading="tableLoading"
      :scroll="{ x: 1200 }"
      row-key="employeeId"
      bordered
      :row-selection="{ selectedRowKeys: selectedRowKeyList }"
    >
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record)" type="link">编辑</a-button>
            <a-button @click="onDelete(record)" danger type="link">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="params.pageSize"
        v-model:current="params.pageNum"
        v-model:pageSize="params.pageSize"
        :total="total"
        @change="queryEmployee"
        @showSizeChange="queryEmployee"
        :show-total="showTableTotal"
      />
    </div>
    <EmployeeFormModal ref="employeeFormModal" @refresh="queryEmployee" @show-account="showAccount" />
    <EmployeeDepartmentFormModal ref="employeeDepartmentFormModal" @refresh="queryEmployee" />
    <EmployeePasswordDialog ref="employeePasswordDialog" />
    <MaterialBaseForm ref="formRef" @reloadList="queryData" />
  </a-card>
</template>
<script setup lang="ts">
  // import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { computed, createVNode, reactive, ref, watch, onMounted } from 'vue';
  // import { employeeApi } from '/@/api/system/employee-api';
  import { PAGE_SIZE } from '/@/constants/common-const';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import EmployeeFormModal from '../employee-form-modal/index.vue';
  import EmployeeDepartmentFormModal from '../employee-department-form-modal/index.vue';
  import EmployeePasswordDialog from '../employee-password-dialog/index.vue';
  import { PAGE_SIZE_OPTIONS, showTableTotal } from '/@/constants/common-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import { materialBaseApi } from '/@/api/business/material-base/material-base-api';
  import MaterialBaseForm from '../../components/MaterialBase-form.vue';
  // ----------------------- 以下是字段定义 emits props ---------------------

  const props = defineProps({
    departmentId: Number,
    breadcrumb: Array,
  });

  //-------------回显账号密码信息----------
  let employeePasswordDialog = ref();
  function showAccount(accountName, passWord) {
    employeePasswordDialog.value.showModal(accountName, passWord);
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  const queryFormState = {
    materialId: undefined, //物料
    projectId: undefined, //项目
    projectMaterialCode: undefined, //项目用物料编码
    disabledFlag: '',
    registrant: undefined, //供应商
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });

  // ----------------------- 表格/列表/ 搜索 ---------------------
  //字段
  const columns = ref([
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      ellipsis: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      ellipsis: true,
    },
    {
      title: '供应商',
      dataIndex: 'companyName',
      ellipsis: true,
    },
    {
      title: '采购价',
      dataIndex: 'purchasePrice',
      ellipsis: true,
      // render: (text, record) => {
      //   return `${record.purchasePrice}`;
      //   // return String(record.purchasePrice);
      // },
    },
    {
      title: '型号',
      dataIndex: 'specification',
      ellipsis: true,
    },
    {
      title: '规格',
      dataIndex: 'parameter',
      ellipsis: true,
    },

    // {
    //   title: '采购价',
    //   dataIndex: 'disabledFlag',
    //   ellipsis: true,
    // },
    // {
    //   title: '是否禁用',
    //   dataIndex: 'disabledFlag',
    //   ellipsis: true,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   ellipsis: true,
    // },
    // {
    //   title: '修改时间',
    //   dataIndex: 'updateTime',
    //   ellipsis: true,
    // },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 90,
    },
  ]);
  const tableData = ref();

  let defaultParams = {
    departmentId: undefined,
    disabledFlag: false,
    keyword: undefined,
    searchCount: undefined,
    pageNum: 1,
    pageSize: PAGE_SIZE,
    sortItemList: undefined,
  };
  const params = reactive({ ...defaultParams });
  const total = ref(0);

  // 表格数据
  const PaginationForm = reactive({
    categoryId: undefined,
    materialName: undefined,
    model: undefined,
    supplier: undefined,
    // disabledFlag: undefined,
    materialCode: undefined,
    purchasePrice: undefined,
    pageNum: 1,
    pageSize: 10,
  });

  // 搜索重置
  function reset() {
    Object.assign(params, defaultParams);
    queryEmployee();
  }

  const formRef = ref();

  function showForm(data) {
    formRef.value.show(data);
  }

  const tableLoading = ref(false);
  // 查询
  async function queryEmployee() {
    tableLoading.value = true;
    try {
      PaginationForm.categoryId = props.departmentId;
      let queryResult = await materialBaseApi.PaginationQuery(PaginationForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;

      // 清除选中
      // selectedRowKeys.value = [];
      selectedRows.value = [];
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      tableLoading.value = false;
    }
  }
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }
  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await materialBaseApi.delete(data.id);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }
  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要批量删除这些数据吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestBatchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }
  //请求批量删除
  async function requestBatchDelete() {
    try {
      SmartLoading.show();
      await materialBaseApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  watch(
    () => props.departmentId,
    () => {
      if (props.departmentId !== params.departmentId) {
        params.pageNum = 1;
        queryEmployee();
      }
    },
    { immediate: true }
  );

  // ----------------------- 多选操作 ---------------------

  let selectedRowKeyList = ref([]);
  let selectedRows = ref([]);

  const formDefault1 = reactive({
    categoryType: 2,
    parentId: '',
  });
  const dictValueList = ref([]);
  async function queryDict2() {
    let res = await materialBaseApi.ClassificationData(formDefault1);
    dictValueList.value = res.data;
  }

  onMounted(() => {
    queryDict2();
    queryData();
  });
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await materialBaseApi.PaginationQuery(PaginationForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
      for (let i = 0; i < tableData.value.length; i++) {
        let obj = dictValueList.value.filter((e) => {
          return e.categoryId == tableData.value[i].categoryId;
        });
        tableData.value[i].categoryName = obj[0].categoryName;
      }
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
</script>
<style scoped lang="less">
  .employee-container {
    height: 100%;
  }
  .query-operate {
    margin-left: auto;
    display: flex;
    align-items: center;
  }

  .btn-group {
    margin: 10px 0;
    .btn {
      margin-right: 8px;
    }
  }
</style>
